package com.zh.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zh.common.BaseResponse;
import com.zh.common.ErrorCode;
import com.zh.common.ResultUtils;
import com.zh.domain.dto.message.MessageQueryRequest;
import com.zh.domain.dto.message.MessageReadRequest;
import com.zh.domain.entity.MessageReceiver;
import com.zh.domain.vo.message.MessageVo;
import com.zh.exception.ThrowUtils;
import com.zh.service.MessageReceiverService;
import com.zh.service.MessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Api(tags = "MessageController", value = "消息控制器")
@RestController
@RequestMapping("/message")
@Slf4j
@SaCheckLogin
public class MessageController {

    private final MessageService messageService;

    private final MessageReceiverService messageReceiverService;

    public MessageController(MessageService messageService, MessageReceiverService messageReceiverService) {
        this.messageService = messageService;
        this.messageReceiverService = messageReceiverService;
    }

    @PostMapping("/page")
    @ApiOperation(value = ("pageMessage"), notes = "分页查询消息")
    public BaseResponse<Page<MessageVo>> pageMessage(@RequestBody MessageQueryRequest messageQueryRequest) {
        ThrowUtils.throwIf(null == messageQueryRequest, ErrorCode.PARAMS_ERROR);
        Page<MessageVo> result = messageService.pageMessages(messageQueryRequest);
        return ResultUtils.success(result);
    }

    @GetMapping("/unreadCount")
    @ApiOperation(value = "unreadCount", notes = "查询未读消息数量")
    public BaseResponse<Integer> UnreadCount(Integer userId) {
        int selectId = StpUtil.getLoginIdAsInt();
        if (userId != null) {
            selectId = userId;
        }
        LambdaQueryWrapper<MessageReceiver> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MessageReceiver::getReceiverId, selectId)
                .eq(MessageReceiver::getStatus, 1)
                .eq(MessageReceiver::getDeleted, 0);
        long count = messageReceiverService.count(queryWrapper);
        return ResultUtils.success((int) count);
    }

    @PostMapping("/read")
    @ApiOperation(value = "read", notes = "标记消息为已读")
    public BaseResponse<Boolean> read(@RequestBody MessageReadRequest messageReadRequest) {
        ThrowUtils.throwIf(messageReadRequest == null, ErrorCode.PARAMS_ERROR);
        boolean b = messageService.read(messageReadRequest);
        return ResultUtils.success(b);
    }
}
